/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.thu.laud.objectstore;

import java.util.HashSet;
import java.util.Set;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.thrift.TException;
import org.datanucleus.exceptions.NucleusDataStoreException;
import org.datanucleus.metadata.AbstractClassMetaData;
import org.datanucleus.metadata.MetaDataListener;
import cn.edu.thu.laud.utils.CassandraUtils;
import cn.edu.thu.laud.utils.MetaDataUtils;
import org.datanucleus.util.Localiser;

/**
 * Listener for the load of metadata for classes.Create column families and index columns if they do not exist when a class is
 * loaded the first time.
 * Allows us to reject metadata when it isn't supported by this datastore.
 * @author zhuoan
 */
public class CassandraMetaDataListener implements MetaDataListener{

	 /** Localiser for messages. */
    protected static final Localiser LOCALISER = Localiser.getInstance(
        "cn.edu.thu.laud.objectstore.Localisation", CassandraStoreManager.class.getClassLoader());

    private CassandraStoreManager storeManager;
    private Set<String> visitedCfs = new HashSet<String>();
    private Object mutex = new Object();
	private boolean createColumnFamilies;
	 
    CassandraMetaDataListener(CassandraStoreManager storeManager, boolean createColumnFamilies)
    {
        this.storeManager = storeManager;
        this.createColumnFamilies = createColumnFamilies;
    }
	
	
	@Override
	public void loaded(AbstractClassMetaData cmd) {
		
		String cfName = MetaDataUtils.getColumnFamily(cmd);

		// shouldn't check the keyspace
		if (cfName == null) {
			return;
		}

		if (visitedCfs.contains(cfName)) {
			return;
		}

		synchronized (mutex) {
			// could be the second into the mutex
			if (visitedCfs.contains(cfName)) {
				return;
			}
						
			// now go through the corresponding fields and create our indexes

			boolean schemaChanged = false;
			CassandraConnectionInfo connectionInfo = storeManager
		                .getConnectionInfo();
		    Cassandra.Client client = CassandraUtils.getConnection(connectionInfo);
		    KsDef ks;
			try {
				ks = client.describe_keyspace(connectionInfo.getKeyspace());
				
				if (createColumnFamilies) {
					client.set_keyspace(connectionInfo.getKeyspace());
					schemaChanged = CassandraUtils.createCf(client, ks, cfName);
				}
				
				//wait for every online node to ack the column family and indexes.  If one fails sleep and try it again
				if(schemaChanged){
				       try {
						Thread.sleep(connectionInfo.getCheckSleepTime());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						
					}
				}
				
				
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				throw new NucleusDataStoreException(e.getMessage(), e);
			} catch (InvalidRequestException e) {
				// TODO Auto-generated catch block
				throw new NucleusDataStoreException(e.getMessage(), e);
			} catch (TException e) {
				// TODO Auto-generated catch block
				throw new NucleusDataStoreException(e.getMessage(), e);
			}
			
		
		}
		
	}
	
}
